#include "games/memorygame.h"

MemoryGame::MemoryGame(QWidget *parent, int difflvl) :
    BaseGame(parent, difflvl)
{
    n_rows = 2 + difficulty_level * 2;
    n_cols = 2 + difficulty_level;
    int colors = n_rows * n_cols / 2;

    QList<QColor> list;
    for(int i = 0; i < colors; i++) {
        QColor color = QColor(qrand() % 255, qrand() % 255, qrand() % 255);
        list << color;
        list << color;
    }

    last_r = -1;
    last_c = -1;

    QSignalMapper* signalMapper = new QSignalMapper (this);
    QSignalMapper* signalMapperTimeout = new QSignalMapper (this);

    map = new QPushButton**[n_rows];
    color_map = new QColor*[n_rows];
    bool_map = new bool*[n_rows];
    timer_map = new QTimer**[n_rows];


    for(int r = 0; r < n_rows; r++) {
        map[r] = new QPushButton*[n_cols];
        color_map[r] = new QColor[n_cols];
        bool_map[r] = new bool[n_cols];
        timer_map[r] = new QTimer*[n_cols];

        for(int c = 0; c < n_cols; c++) {
            QPushButton * p = new QPushButton(this);
            color_map[r][c] = list.takeAt(qrand() % ((colors * 2) - r * n_cols - c) );
            bool_map[r][c] = false;
            QTimer * t = new QTimer();

            timer_map[r][c] = t;
            map[r][c] = p;
            t->setInterval(1000);
            lay->addWidget(p, r, c);

            connect(p, SIGNAL(clicked()), signalMapper, SLOT(map()));
            signalMapper->setMapping(p, r * n_cols + c);
            connect(t, SIGNAL(timeout()), signalMapperTimeout, SLOT(map()));
            signalMapperTimeout->setMapping(t, r * n_cols + c);
        }
    }

    connect (signalMapper, SIGNAL(mapped(int)), this, SLOT(onButtonClicked(int)));
    connect (signalMapperTimeout, SIGNAL(mapped(int)), this, SLOT(onTimeout(int)));
}

bool MemoryGame::isSolved()
{
        for(int r = 0; r < n_rows; r++) {
            for(int c = 0; c < n_cols; c++) {
                if(bool_map[r][c] == false) return false;
            }
        }
        return true;
}

void MemoryGame::onTimeout(int index)
{
    int row = index / n_cols;
    int col = index % n_cols;

    map[row][col]->setPalette(QPalette());
    timer_map[row][col]->stop();
}

void MemoryGame::onButtonClicked(int index)
{
    int row = index / n_cols;
    int col = index % n_cols;

    if(last_r == row && last_c == col) return;
    if(bool_map[row][col] == true) return;

    map[row][col]->setPalette(color_map[row][col]);

    if( last_r != -1 && color_map[row][col] == color_map[last_r][last_c] ) {
        bool_map[row][col] = true;
        bool_map[last_r][last_c] = true;
        timer_map[last_r][last_c]->stop();
        map[last_r][last_c]->setPalette(color_map[last_r][last_c]);
    } else {
        timer_map[row][col]->start();
    }

    last_r = row;
    last_c = col;
}
